<script setup lang="ts">
import { fetchRecordDetails, type LogDataRecord } from '@/api/admin/historyRecord'
import { rate } from '@/api/admin/public'

const router = useRouter()

const query = (useRoute().query || {
  medical_record_number: '',
  created_date: '',
}) as {
  medical_record_number: string
  created_date: string
}

const rateResult = ref()
const currentQuestionIndex = ref(0)
const submittedAnswers = ref<number[]>([])

const recordDetails = ref<LogDataRecord | null>(null)

interface HandwritingGroup {
  timestamp: string
  videoPath: string
  imagePath: string
}

const handwritingGroups = computed<HandwritingGroup[]>(() => {
  if (!recordDetails.value?.handwriting) return []

  const handwritingData = recordDetails.value.handwriting
  const groups: { [key: string]: HandwritingGroup } = {}

  // 提取时间戳并分组
  Object.entries(handwritingData).forEach(([key, path]) => {
    // 从文件名中提取时间戳
    const timestampMatch = key.match(/(\d{14})/)
    if (timestampMatch) {
      const timestamp = timestampMatch[1]

      if (!groups[timestamp]) {
        groups[timestamp] = {
          timestamp,
          videoPath: '',
          imagePath: '',
        }
      }

      // 判断是视频还是图片
      if (key.includes('.mp4')) {
        groups[timestamp].videoPath = path as string
      } else if (key.includes('.png')) {
        groups[timestamp].imagePath = path as string
      }
    }
  })

  // 按时间戳排序
  return Object.values(groups).sort((a, b) => a.timestamp.localeCompare(b.timestamp))
})

const currentGroup = computed(() => {
  return handwritingGroups.value[currentQuestionIndex.value] || null
})

const getRecordDetails = async () => {
  try {
    const response = await fetchRecordDetails(query.medical_record_number, query.created_date)
    if (response) {
      recordDetails.value = response
      // 初始化提交答案数组
      submittedAnswers.value = new Array(handwritingGroups.value.length).fill(-1)
    }
  } catch (error: any) {
    ElMessage.error(error?.errorDetails.description || error?.message || '未知错误')
  }
}

const question = ref<Record<string, string>>({})

const fechQuestion = async () => {
  try {
    const response = await fetch('http://localhost:8000/static/hand.json')
    if (response.ok) {
      question.value = await response.json()
    }
  } catch (error: any) {
    ElMessage.error('获取评分失败')
    console.error('获取评分失败: ', error)
  }
}

const handleSubmit = async () => {
  if (!rateResult.value && rateResult.value !== 0) {
    ElMessage.warning('请先选择评分')
    return false
  }

  // 保存当前题目答案
  submittedAnswers.value[currentQuestionIndex.value] = rateResult.value

  try {
    await rate({
      medical_record_number: query.medical_record_number,
      created_date: query.created_date,
      category: 'handwriting',
      score: rateResult.value,
    })

    ElMessage.success('提交成功')

    // 如果是最后一题，跳转到下一个页面
    if (currentQuestionIndex.value >= handwritingGroups.value.length - 1) {
      router.push({
        path: '/speech',
        query: {
          medical_record_number: query.medical_record_number,
          created_date: query.created_date,
        },
      })
    }
  } catch (error) {
    ElMessage.error('评分失败')
    console.error('评分失败: ', error)
  }
}

const handleNext = () => {
  if (currentQuestionIndex.value < handwritingGroups.value.length - 1) {
    currentQuestionIndex.value++
    // 清空当前题目答案
    rateResult.value = 0
  }
}

const handleBack = () => {
  router.push({
    path: '/eyeMovement',
    query: {
      medical_record_number: query.medical_record_number,
      created_date: query.created_date,
    },
  })
}

const videoSrc = computed(() => {
  if (!currentGroup.value?.videoPath) return ''
  const src = `http://localhost:8000/${currentGroup.value.videoPath}`.replace(/\\+/g, '/')
  return src
})

const imageSrc = computed(() => {
  if (!currentGroup.value?.imagePath) return ''
  const src = `http://localhost:8000/${currentGroup.value.imagePath}`.replace(/\\+/g, '/')
  return src
})

const isSubmitted = computed(() => {
  return submittedAnswers.value[currentQuestionIndex.value] >= 0
})

const canShowNext = computed(() => {
  return (
    !handwritingGroups.value?.length ||
    (isSubmitted.value && currentQuestionIndex.value < handwritingGroups.value.length - 1)
  )
})

onMounted(() => {
  fechQuestion()
  getRecordDetails()
})
</script>

<template>
  <el-row :gutter="48" class="h-full -mr-6">
    <el-col :span="12" class="pr-4">
      <!-- 显示当前题目信息 -->
      <div class="mb-4 text-brand text-lg">
        题目 {{ currentQuestionIndex + 1 }} / {{ handwritingGroups.length }}
      </div>

      <!-- 视频显示 -->
      <div class="mb-4">
        <video
          v-if="videoSrc"
          :src="videoSrc"
          controls
          class="w-full max-h-60 object-contain"
          preload="metadata"
        >
          您的浏览器不支持视频播放
        </video>
        <div v-else class="w-full h-60 bg-gray-100 flex items-center justify-center text-gray-500">
          暂无视频
        </div>
      </div>

      <!-- 图片显示 -->
      <div>
        <img
          v-if="imageSrc"
          :src="imageSrc"
          class="w-full max-h-60 object-contain"
          alt="手写轨迹图"
        />
        <div v-else class="w-full h-60 bg-gray-100 flex items-center justify-center text-gray-500">
          暂无图片
        </div>
      </div>
    </el-col>

    <el-col :span="12" class="h-full overflow-auto pr-6">
      <div class="text-brand text-2xl">当前结果：</div>
      <div class="text-#00BA3D font-500 mt-4">
        <span class="text-4xl">{{ rateResult || 0 }}</span>
        <span class="text-lg ml-1">分</span>
      </div>
      <div class="text-brand text-lg mt-4">{{ question[rateResult] || '' }}</div>

      <el-radio-group v-model="rateResult" class="mt-4">
        <el-radio v-for="rate in Object.keys(question)" :key="rate" :value="Number(rate)">
          {{ question[rate] }}
        </el-radio>
      </el-radio-group>

      <div class="flex items-center justify-evenly gap-4 mt-12">
        <el-button v-if="!isSubmitted" type="primary" class="flex-1" @click="handleSubmit">
          提交结果
        </el-button>

        <el-button v-if="canShowNext" type="success" class="flex-1" @click="handleNext">
          下一题
        </el-button>

        <el-button class="brand-dark-button flex-1" @click="handleBack">返回上一页</el-button>
      </div>
    </el-col>
  </el-row>
</template>

<style lang="css" scoped>
:deep(.el-radio) {
  display: block;
  width: 100%;
}
:deep(.el-radio) {
  --el-color-primary: #508bcc;
  --el-radio-font-size: 16px;
  margin-bottom: 8px;
}
:deep(.el-button) {
  padding: 18px 0;
}
</style>
